package org.example.coupon.service.impl;

import org.example.core.constant.TokenConstants;
import org.example.coupon.dao.CouponDao;
import org.example.coupon.dao.CouponHistoryDao;
import org.example.coupon.dao.CouponSpuCategoryRelationDao;
import org.example.coupon.to.CouponTo;
import org.example.coupon.vo.CouponVo;
import org.example.security.handler.SecurityHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.coupon.service.CouponHistoryService;

import java.util.List;


@Service("couponHistoryService")
public class CouponHistoryServiceImpl implements CouponHistoryService {

    @Autowired
    private CouponHistoryDao couponHistoryDao;

    @Autowired
    private CouponDao couponDao;

    @Autowired
    private CouponSpuCategoryRelationDao couponSpuCategoryRelationDao;

    @Override
    public List<CouponTo> queryCouponMember() {
        String memberId = SecurityHandler.getData().get(TokenConstants.MEMBER_ID);
        // 拥有的可以使用的优惠劵
        List<Long> couponIds = couponHistoryDao.getUseCouponIdsByMemberId(Long.parseLong(memberId));
        // 获取到优惠卷信息
        if (couponIds != null && couponIds.size()>0){
            List<CouponTo> tos = couponDao.getCouponListByIds(couponIds);
            if (tos != null && tos.size()>0){
                for (CouponTo to : tos) {
                    if (to.getUseType() == 1){
                        List<Long> categoryIds = couponSpuCategoryRelationDao.getCouponCategoryIds(to.getCouponId());
                        to.setCategoryIds(categoryIds);
                    }
                }
                return tos;
            }
        }
        return null;
    }

    // 验证优惠卷金额
    @Override
    public CouponVo queryCouponIsUsed(Long couponId) {
        String memberId = SecurityHandler.getData().get(TokenConstants.MEMBER_ID);
        int count = couponHistoryDao.getUseCouponId(couponId, Long.parseLong(memberId));
        if (count > 0){
            CouponVo couponVo = couponDao.getCouponAmount(couponId);
            if (couponVo != null){
                return couponVo;
            }
            return null;
        }
        return null;
    }
}